package com.ncloud.product.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.exception.UserException;
import com.ncloud.product.common.Constant;
import com.ncloud.product.entity.Discnt;
import com.ncloud.product.entity.DiscntPrice;
import com.ncloud.product.entity.ProdItem;
import com.ncloud.product.mapper.PriceItemMapper;
import com.ncloud.product.mapper.PriceMapper;
import com.ncloud.product.mapper.ProdItemMapper;

@Service
public class DiscntPriceServiceImpl{
	
	@Autowired
	private ProdItemMapper prodItemMapper;
	@Autowired
	private PriceItemMapper priceItemMapper;
	@Autowired
	private PriceMapper priceMapper;
	
	public Long getPriceByItems(JSONObject json) {
		Long prodId = json.getLong("prodId");
		Long discntId = json.getLong("discntId");
		String nodeType = json.getString("nodeType");
		//1、获取产品对应属性
		List<ProdItem> items = prodItemMapper.getProdItems(prodId,nodeType);
		//2、判断传入参数中是否存在属性，不存在抛出异常
		List<Long> resultList = new ArrayList<Long>();
		for (ProdItem prodItem : items) {
			if(!json.containsKey(prodItem.getItemCode())){
				throw new UserException("2001","缺少传入参数，无法查找资费");
			}
			//3、根据属性查找定价编码
			String value = json.getString(prodItem.getItemCode());
			List<Long> priceList = priceItemMapper.getPriceByItem(prodId,discntId,prodItem.getItemCode(),value);
			if(resultList.isEmpty()) resultList.addAll(priceList);
			else resultList.retainAll(priceList);
		}
		if(resultList.isEmpty()) throw new UserException("2002","没有匹配的价格");
		if(resultList.size()>1) throw new UserException("2003","匹配到多条价格");
		return resultList.get(0);
	}

	public DiscntPrice getByPriceId(Long priceId) {
		return priceMapper.getByPriceId(priceId);
	}

	public List<DiscntPrice> getDiscntPriceByDiscnt(Long discntId) {
		List<DiscntPrice> discntPrices = priceMapper.getDiscntPriceByDiscnt(discntId);
		return discntPrices;
	}

	public DiscntPrice getDiscntFeeByDiscnt(Discnt discnt) {
		if(Constant.DISCNT_TYPE_BASEFEE.equals(discnt.getDiscntType())){
			return null;
		}
		List<DiscntPrice> prices = getDiscntPriceByDiscnt(discnt.getDiscntId());
		if(prices!=null && prices.size()==1) {
			DiscntPrice price = prices.get(0);
			return price;
		}else{
			// 暂时不处理
		}
		//if(prices.size() != 1) throw new UserException("配置错误，非基础套餐只能配置一条费用，discntId="+discnt.getDiscntId());
		
		return null;
	}
	
}
